/*
 * This file (AxLogDlg.java) is protected by the GNU GPL licence (v2). 
 * Please read the license.txt attached for further informations. 
 * 
 */

package artx.gui;

import java.awt.ComponentOrientation;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;

import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

import artx.events.AxLogEvent;
import artx.listeners.AxLogListener;
import artx.utils.AxConstants;
import artx.utils.AxLog;

/**
 * Simple gui to display all log messages {@link artx.utils.AxLog}.
 * 
 * @author Xavier Gouchet
 * 
 */
public class AxLogDlg extends JDialog implements AxLogListener, AxConstants {

	private static final long serialVersionUID = 1L;

	private JPanel mainPanel = null;

	private JTextArea logTextArea = null;

	private JScrollPane logScrollPane = null;

	/**
	 * Standard constructor.
	 * 
	 * @param owner
	 *            the master window calling this dialog
	 * @param title
	 *            the title of the dialog
	 */
	public AxLogDlg(Frame owner, String title) {
		super(owner);
		this.setSize(420, 260);
		this.setMinimumSize(new Dimension(480, 260));
		this.setResizable(false);
		this.setTitle(title);
		this.setContentPane(this.getMainPanel());
		AxLog.AddLogListener(this);
	}

	private JPanel getMainPanel() {
		if (this.mainPanel == null) {
			this.mainPanel = new JPanel();
			this.mainPanel.setLayout(new GridBagLayout());
			this.mainPanel
					.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);

			GridBagConstraints gbc = new GridBagConstraints();
			gbc.fill = GridBagConstraints.BOTH;
			gbc.gridx = 0;
			gbc.gridy = 0;
			gbc.weightx = 1.0;
			gbc.weighty = 1.0;
			gbc.insets = new Insets(4, 0, 0, 0);

			this.logScrollPane = new JScrollPane();
			this.logScrollPane.setViewportView(this.getLogTextArea());
			this.mainPanel.add(this.logScrollPane, gbc);
		}
		return this.mainPanel;
	}

	private JTextArea getLogTextArea() {
		if (this.logTextArea == null) {
			this.logTextArea = new JTextArea();
			this.logTextArea.setEditable(false);
			String[] log = AxLog.GetDebugLog();
			if (log != null) {
				for (int i = 0; i < log.length; i++) {
					this.logTextArea.append(log[i] + "\n");
				}
			}
		}
		return this.logTextArea;
	}

	/**
	 * @see artx.listeners.AxLogListener#debugMessageRegistered(artx.events.AxLogEvent)
	 */
	public void debugMessageRegistered(AxLogEvent evt) {
		if (this.logTextArea != null) {
			this.logTextArea.append(evt.GetMessage() + "\n");
			int val = this.logScrollPane.getVerticalScrollBar().getMaximum();
			this.logScrollPane.getVerticalScrollBar().setValue(val);
		}
	}

	/**
	 * @see artx.listeners.AxLogListener#messageRegistered(artx.events.AxLogEvent)
	 */
	public void messageRegistered(AxLogEvent evt) {
	}

}
